package solutions.leetcode.normal


/**
 * @author lizhidong
 * <a href="https://leetcode.cn/problems/greatest-sum-divisible-by-three/">1262. 可被三整除的最大和</a>
 */
class Solution1262() {
    fun maxSumDivThree(nums: IntArray): Int {
        val single = intArrayOf(10001, 10001)
        val double = intArrayOf(10001, 10001)
        var sum = 0
        for (num in nums) {
            sum += num
            when (num % 3) {
                1 -> saveMin(single, num)
                2 -> saveMin(double, num)
            }
        }
        return when (sum % 3) {
            1 -> {
                if (single[0] < double[0] + double[1]) {
                    sum - single[0]
                } else sum - double[0] - double[1]
            }

            2 -> {
                if (single[0] + single[1] < double[0]) {
                    sum - single[0] - single[1]
                } else sum - double[0]
            }

            else -> sum
        }
    }

    fun saveMin(nums: IntArray, target: Int) {
        val max = Math.max(target, Math.max(nums[0], nums[1]))
        if (max == target) {
            return
        }
        val a = Math.min(nums[0], nums[1])
        nums[0] = Math.min(a, target)
        nums[1] = a + target - nums[0]
    }
}

fun main() {
    val solution = Solution1262()
    println(solution.maxSumDivThree(intArrayOf(
        3,6,5,1,8
    )))
}